package kuang;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @author cyt
 * @create 2020-03-07 9:26
 */
public class TestCallable implements Callable<String> {
    private String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583553668183&di=e63b1dd525905bde37fef9da3e5a09cc&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F36%2F48%2F19300001357258133412489354717.jpg";

    void down(String name) throws IOException {
        FileUtils.copyURLToFile(new URL(url), new File(name));
    }

    @Override
    public String call() throws Exception {
        String s = null;
        for (int i = 0; i < 3; i++) {
            try {
                down(Integer.toString(i) + Thread.currentThread().getName());

                s = i + " " + Thread.currentThread().getName();
                System.out.println("name :" + s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable();
        TestCallable t2 = new TestCallable();
        TestCallable t3 = new TestCallable();


        // 创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<String> s1 = service.submit(t1);
        Future<String> s2 = service.submit(t2);
        Future<String> s3 = service.submit(t3);


        // 获得结果
        String n1 = s1.get();
        String n2 = s2.get();
        String n3 = s3.get();

        System.out.println(n1);

        // 关闭服务
        service.shutdown();
    }
}

